package com.hzz.openglstudy.util

import android.content.Context
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * Created by hzz on 2018/6/13.
 */
inline fun Context.readFileFromResource(resId:Int):String{
    val body = StringBuilder()
    val inputStream = resources.openRawResource(resId)
    val streamReader = InputStreamReader(inputStream)
    val bufferedReader = BufferedReader(streamReader)

    var nextLine=bufferedReader.readLine()
    while (nextLine!=null){
        body.append(nextLine)
        body.append("\n")
        nextLine=bufferedReader.readLine()
    }
    return body.toString()
}

inline fun GLSurfaceView.Renderer.compileVertexShader(sharderCode:String):Int{
    return compileShader(GLES20.GL_VERTEX_SHADER,sharderCode)
}

inline fun GLSurfaceView.Renderer.compileFragmentShader(sharderCode:String):Int{
    return compileShader(GLES20.GL_FRAGMENT_SHADER,sharderCode)
}

inline fun GLSurfaceView.Renderer.compileShader(type: Int, shaderCode: String): Int {
    val shaderHandle = GLES20.glCreateShader(type)

    if (shaderHandle == 0) {
        return 0
    }

    GLES20.glShaderSource(shaderHandle, shaderCode)
    GLES20.glCompileShader(shaderHandle)

    val compileStatus = IntArray(1)
    GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0)

    if (compileStatus[0] == 0) {
        GLES20.glDeleteShader(shaderHandle)
        return 0
    }

    return shaderHandle
}

 inline fun GLSurfaceView.Renderer.linkProgram(vertexShaderId:Int,fragmentShaderId:Int):Int{
     val program = GLES20.glCreateProgram()
     if (program == 0) {
         return 0
     }

     //使用attach把顶点和着色器附加到程序上
     GLES20.glAttachShader(program, vertexShaderId)
     GLES20.glAttachShader(program, fragmentShaderId)

     GLES20.glLinkProgram(program)

     val linkStatus = IntArray(1)
     GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0)
     if (linkStatus[0] == 0) {
         GLES20.glDeleteProgram(program)
         return 0
     }
     return program
 }

inline fun GLSurfaceView.Renderer.validateProgram(program: Int) :Boolean{
    GLES20.glValidateProgram(program)

    val validateStatus = IntArray(1)

    GLES20.glGetProgramiv(program, GLES20.GL_VALIDATE_STATUS, validateStatus, 0)
    return validateStatus[0]!=0
}